package com.gitee.jisong.springboot;

import com.gitee.jisong.api.ChangeLogLevelProcess;
import com.gitee.jisong.bean.LoggerBean;
import com.gitee.jisong.enums.LogLevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyEditorSupport;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author sunjisong 2019-07-29
 */
@RestController
@RequestMapping("/xlogger")
public class XLoggerController {

    private static final Logger logger = LoggerFactory.getLogger(XLoggerController.class);

    @RequestMapping(value = "/getLoggers",method = RequestMethod.GET)
    public Map<String, Object> getLoggers(){
        return ChangeLogLevelProcess.getInstance().getLoggerInfos();
    }

    @RequestMapping(value = "/setLogger",method = {RequestMethod.POST,RequestMethod.GET})
    public String setLogger(String name, LogLevel level){
        ChangeLogLevelProcess instance = ChangeLogLevelProcess.getInstance();
        LoggerBean bean = new LoggerBean();
        bean.setLevel(level);
        bean.setName(name);
        List<LoggerBean> lists = new ArrayList<>();
        lists.add(bean);
        try{
            instance.process(lists);
        }catch (Exception e){
            logger.warn("set logger : {} - {} failed." , name , level);
            return e.getMessage();
        }
        return "SUCCESS";
    }


    @RequestMapping(value = "/batchLoggers",method = {RequestMethod.POST,RequestMethod.GET})
    public String setLoggers(List<LoggerBean> lists){
        ChangeLogLevelProcess instance = ChangeLogLevelProcess.getInstance();
        try{
            instance.process(lists);
        }catch (Exception e){
            return e.getMessage();
        }
        return "SUCCESS";
    }

    @InitBinder
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
        binder.registerCustomEditor(
                LogLevel.class,new PropertyEditorSupport(){
                    @Override
                    public void setAsText(String text)  throws IllegalArgumentException {
                        setValue(LogLevel.getByDef(text,LogLevel.INFO));
                    }
                });
    }

}
